package com.qlhx.timer;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.qlhx.common.util.DateUtil;
import com.qlhx.core.HTTP;
import com.qlhx.core.MD5;
import com.qlhx.core.Security;
import com.qlhx.dao.SyncDataMethod;
import com.qlhx.model.SyncDataManager;
import com.qlhx.wechat.common.util.HardWareUtils;
import com.qlhx.wechat.common.util.SpringContextUtil;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Create by byl
 *
 * @versio 1.0.0
 * @Author baiyanlong
 * @date 2019/7/22 16:40
 * @description desc:
 */
public class SycDateUtil {

        private SyncDataManager syncDataManager = SpringContextUtil.getBean(
                "syncdataManager", SyncDataManager.class);

        // 图片上传url
        //private String imguploadurl = IConfig.get("imguploadurl");

        /**
         * 实体包名
         */
        //private String modelName = "com.qlhx.model.";

        /**
         * 数据持久层包名
         */
        private String daoName = "com.qlhx.dao.";

        /**
         * 数据同步
         * @return int 大于0成功
         * @throws Exception
         */
        public void syncData( String dataUploadUrl , String areaCode) throws Exception {

        Map<String, Map<String, Map<String, String>>> map = syncDataManager
                .getConfigitem();
        for (Map.Entry<String, Map<String, Map<String, String>>> entry : map
                .entrySet()) {
            String className = entry.getKey();// 实体类名
            String beanName = daoName + className + "Mapper";// dao类完整路径名称
            SqlSessionTemplate sdm = SpringContextUtil.getApplicationContext()
                    .getBean("sqlSessionTemplate", SqlSessionTemplate.class);
            SqlSession sqlsession = sdm.getSqlSessionFactory().openSession();
            Class<?> c = Class.forName(beanName);
            SyncDataMethod method = (SyncDataMethod) sqlsession.getMapper(c);
            // 获取同步数据
            List<Object> list = method.syncData(syncDataManager.getNum());
            if (list == null || (list != null && list.size() == 0)) {
                System.out.println("未获取到数据" + className);
                sqlsession.close();
                continue;
            }
            String picredieskey ="";
            // 处理同步数据
            for (Object object : list) {
                Class cl = (Class) object.getClass();
                Field[] fs = cl.getDeclaredFields();
                for (int i = 0; i < fs.length; i++) {
                    Field f = fs[i];
                    f.setAccessible(true); // 设置属性可以访问
                    Map<String, Map<String, String>> map2 = entry.getValue();
                    for (Map.Entry<String, Map<String, String>> entry2 : map2
                            .entrySet()) {
                        if (entry2.getKey().equals(f.getName())) {
                            Map<String, String> map3 = entry2.getValue();
                            for (Map.Entry<String, String> entry3 : map3
                                    .entrySet())
                            {
                                if (entry3.getKey().equals("r")) {// 替换内容
                                    f.set(object, entry3.getValue());
                                }
                            }
                        }else if (f.getType().isInstance(new Date()) && f.get(object) != null){
                            Date date = DateUtil.convertToDateByPattern(f.get(object).toString(), "yyyy-MM-dd HH:mm:ss");
                            f.set(object,date);
                        }
                    }

                }
            }


            // 数据上传
            String liststr = JSONArray
                    .toJSONString(list, SerializerFeature.WriteMapNullValue)
                    .replace("\t", "").replace("\n", "").replace("\r", "");
            String data = Security.getBase64String(liststr);// 数据
            // String data = "123";// 数据
            //System.out.println("base64_json:" + data);
            //System.out.println("base64_decode_json:"   + Security.getBase64Decode(data));

            //System.out.println("jsonSize:" + data.length());
            long timestamp = System.currentTimeMillis();// 时间戳
            String sign = MD5.getMD5_32(data + className + timestamp);
            JSONObject jsonData = new JSONObject();
            jsonData.put("data", data);
            jsonData.put("timestamp", timestamp);
            jsonData.put("className", className);
            jsonData.put("sign", sign);
            // System.out.println("jsonData:" + jsonData.toJSONString());
            // 上传数据
            String result = HTTP.post(dataUploadUrl+"/dataSync?token="+ HardWareUtils.GetLocalAuthCode()+"&areaCode="+areaCode, jsonData.toJSONString());
            JSONObject rejson = JSONObject.parseObject(result);
            //System.out.println(className + "--同步返回:" + rejson);
            if (result != null && !"".equals(result) && rejson != null
                    && rejson.getIntValue("code") == 1000) {// 同步成功
                String idlist = "";
                // 修改同步数据时间
                for (Object object : list) {
                    Class cl = (Class) object.getClass();
                    Field[] fs = cl.getDeclaredFields();
                    Long id = 0l;
                    Date time = new Date();
                    for (int i = 0; i < fs.length; i++) {
                        Field f = fs[i];
                        f.setAccessible(true); // 设置属性可以访问
                        // if ("id".equals(f.getName())) {
                        // idlist += f.get(object).toString() + ",";
                        // }
                        if ( "tabtime".equals(f.getName().toLowerCase())
                                || "uploadtime".equals(f.getName().toLowerCase()
                        )) {
                            f.set(object, time);
                        }
                    }
                    if (method.updateUploadStatus(object) > 0) {// 修改状态成功
                        System.out.println("同步数据状态修改成功！");
                    } else {
                        System.out.println("同步数据状态修改失败！");
                    }
                }
            }
            sqlsession.close();// 关闭sqlsession
        }

    }

}
